/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.grapeshot.halfnes;

import static com.grapeshot.halfnes.Client.socket;
import static com.grapeshot.halfnes.Client.writer;
import static com.grapeshot.halfnes.CommunicationInterface.readyMessage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Sebastien Dion & Yome Messena Jean
 */
public class Server implements CommunicationInterface {
    

    private ServerSocket serverSocket;
    InputStream inputStream;
    InputStreamReader reader;
    private Socket clientSocket;    

    protected static BufferedWriter writer;
    protected static BufferedReader bufferedReader;

    public boolean isConnected = false;
    public int receivedByte;
    
    public String clientIp = "";
    
    public void connect() {
        
        Runnable serverTask = new Runnable() {
            @Override
            public void run() {
                try {
                    serverSocket = new ServerSocket(port);
                    System.out.println("Waiting for clients to connect...");
                    clientSocket = serverSocket.accept();                    
                    clientIp = clientSocket.getRemoteSocketAddress().toString();                    
                    System.out.println("Client " + clientIp + " is connected");
                    isConnected = true;                    
                    
                    
                } catch (IOException e) {
                    System.err.println("Unable to process client request");
                    e.printStackTrace();
                }
            }
        };
        Thread serverThread = new Thread(serverTask);
        serverThread.start();
    }
    
    @Override
    public void connect(String ip) {
        throw new UnsupportedOperationException("Server shouldnt connect through IP");
    }
    
    public void readInt() throws IOException {

           try {

            String message = "";            
            int receivedInt = 0;
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            receivedInt = bufferedReader.read();            
            receivedByte = receivedInt;
            
            System.out.println("Server received : " + receivedByte);
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
       
    }
    
    
    public int getReceivedByte() {
        try {
            readInt() ;
        } catch (IOException ex) {
            
            System.out.println("Tried to read" );
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
        return receivedByte;
    }
    
    public void sendData(int byteToSend) {
                try { 
                                        
                    writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
                    if(byteToSend<9999){
                        writer.write(readyMessage);
                    }else{
                        writer.write(byteToSend);  
                    }
                    
                    writer.flush();
                    clientSocket.getOutputStream().flush();

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
    //FIX THIS TRY-CATCH
    public void close(){
         try {
            utils.close(reader);
            utils.close(inputStream);
            utils.close(clientSocket);
            utils.close(serverSocket);
            clientIp = "";
        } catch (IOException ex) {
        }
    }

    @Override
    public String getDistantIp() {
        return clientIp;
    }
    
    
    @Override
    public boolean getConnectionStatus() {
         return isConnected;
    }

    @Override
    public void startListening() throws IOException {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public String readLineServer() {
        
           try {

            String message = "";            
            int receivedInt = 0;
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            message = bufferedReader.readLine();
            System.out.println("Server received : " + message);            
            return message;
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

}
